package net.tbao.authService.controller;


import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import net.tbao.authService.fegin.MenberFeginService;
import net.tbao.authService.fegin.ThirdPartFeginService;
import net.tbao.authService.vo.UserLoginVo;
import net.tbao.authService.vo.UserRegistVo;
import net.tbao.common.constant.AuthServerContstant;
import net.tbao.common.exception.BizCodeEnume;
import net.tbao.common.utils.R;
import net.tbao.common.vo.MenberResponVO;
import org.apache.commons.lang.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LoginController {
    @Autowired
    ThirdPartFeginService thirdPartFeginService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MenberFeginService menberFeginService;

    /**
     * 发送短信验证码 调用第三方服务向阿里云发送验证码
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendConde(@RequestParam("phone") String phone) {

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerContstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            // 获取redis这个key存储的时间
            long l = Long.parseLong(redisCode.split("-")[1]);
            // 判断的是不是60秒内
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnume.VAILD_SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.VAILD_SMS_CODE_EXCEPTION.getMsg());
            }
        }
        // 手机号号和验证码存入redis  5分钟过期
        String code = UUID.randomUUID().toString().substring(0, 5) + "-" + System.currentTimeMillis();
        // TODO redis 缓存验证码

        stringRedisTemplate.opsForValue().set(AuthServerContstant.SMS_CODE_CACHE_PREFIX + phone, code, 10, TimeUnit.MINUTES);

        thirdPartFeginService.sendConde(phone, code);
        return R.ok();
    }

    /**
     * 用户注册
     *
     * @param vo
     * @param result
     * @param model
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String register(UserRegistVo vo, BindingResult result, Model model, RedirectAttributes redirectAttributes) {
        // 校验错误 收集错误信息
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            model.addAttribute("errors", errors);

            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.tbao.cn/reg.html";
        }
        //校验验证码
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerContstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        // 判断验证是否过期
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("-")[0])) {
                //删除验证码 令牌机制
                stringRedisTemplate.delete(AuthServerContstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 验证码正确 调用第三方服务进行注册
                R r = menberFeginService.regist(vo);
                if (r.getCode() == 0) {
                    //注册成功

                    return "redirect:http://auth.tbao.cn/login.html";

                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.tbao.cn/reg.html";
                }
            } else {
                //验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.tbao.cn/reg.html";

            }
            // 注册失败 跳转注册页面
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.tbao.cn/reg.html";
        }

    }

    @GetMapping("/login.html")
    public String LongPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerContstant.LOGIN_USER);
        if(attribute==null){
            return "login";
        }else {
            return "redirect:http://tbao.cn";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        R login = menberFeginService.login(vo);
        if (login.getCode() == 0) {
            MenberResponVO memberRespVo = login.getData("data", new TypeReference<MenberResponVO>() {
            });
            log.info("普通用户登录成功，用户信息：{}", memberRespVo);
            session.setAttribute(AuthServerContstant.LOGIN_USER, memberRespVo);
            return "redirect:http://tbao.cn/";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.tbao.cn/login.html";
        }

    }
}


